#!/bin/sh

#TODO El directorio "tmp" no debe ser relativo. 
OPTIONS="-m 256 -cpu 486 -boot d -no-reboot "
NETWORK="-net nic,model=ne2k_pci,vlan=0 -net user,vlan=0 -redir tcp:8001::80"
BOOT=" -cdrom $2 -hdb current.ext"
PARAMS=" -boot d -m 64 -soundhw sb16,ac97 -localtime"
QEMU="qemu $OPTIONS $NETWORK $PARAMS $BOOT"

if test -z "$LOGDIR"; then
	LOGDIR="../"
fi
LOGFILE="$LOGDIR/$1.log"
#echo "Testing $@ ..."

if test -d "$1"; then
	if test -x $1/pre_script.sh; then
		. $1/pre_script.sh
	fi
	cp test.sample.gz current.ext.gz
	rm -fr current.ext 2>/dev/null
	gunzip current.ext.gz
	mkdir -p tmp
	sudo mount current.ext tmp -o loop 
	sudo rm -fr tmp/*
	sudo cp $1/*.* tmp
	if test -d $1/sysconf; then
		sudo mkdir -p tmp/sysconf
		if test -f $1/sysconf/sysconf.tar; then
			sudo cp $1/sysconf/sysconf.tar tmp/sysconf/
		else
			cd $1/sysconf
			tar -cvf sysconf.tar * >/dev/null
			cd ..
			cd ..
			sudo mv $1/sysconf/sysconf.tar tmp/sysconf/
		fi
	fi
	sudo chmod -R g+w tmp
	sudo chown -R 1000:1000 tmp
	sleep 2
	sudo umount -f tmp
	rm -fr tmp
	
	if $QEMU  2>/dev/null > /dev/null ; then
		mkdir tmp
		sudo mount current.ext tmp -o loop
		TIME=`date +%H:%M:%S` 
		if test -f tmp/result.txt; then
			echo " ---- TEST $1 ---- " >> $LOGFILE
			cat tmp/result.txt >> $LOGFILE
			echo "   $TIME TEST $1 : `tail -n1 tmp/result.txt`"
		else
			echo "   $TIME TEST $1 RESULTS MISSING"
		fi
		sudo umount tmp
		rm -fr tmp
	else
		echo "ERROR: Problem executing qemu with $1"
		exit 1
	fi
	rm current.ext
	if test -x $1/post_script.sh; then
		. $1/post_script.sh
	fi
else
	echo "ERROR: OpenDomo ISO file not specified"
	echo "Usage: $0 [test folder name] [opendomo ISO file]"
	echo
	exit 1
fi
